#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：idi_mes 
@File    ：rabbitmq.py
@IDE     ：PyCharm 
@Author  ：孔令伟
@Date    ：9/18/24 10:16 AM 
"""
import traceback
from inspect import iscoroutinefunction
from mg_app_framework import (get_logger, update_context)
from mg_app_framework.components.rabbitmq_connector import (RabbitMQConfigBasic, rabbitmq_get_subscribe_message_cache)


async def process_mq_msg(msg):
    """

    :param msg:
    :return:
    """
    # 对接收到的消息做初步判断，并分发给对应的处理函数
    msg_key = msg.get('key', None)
    msg_data = msg.get('data', None)
    if not msg_key:
        get_logger().error('msg key is None')
        return
    if msg_key in msg_handler:
        msg_process_func = msg_handler[msg_key]
        if iscoroutinefunction(msg_process_func):
            await msg_process_func(msg_data)
        else:
            msg_process_func(msg_data)


class RabbitMQConfig(RabbitMQConfigBasic):
    """111"""

    def get_rabbitmq_subscribe_list(self):
        """

        :return:
        """
        return my_consume_list

    def message_process_func(self):
        """

        :return:
        """
        return process_mq_msg

    def publish_config_data(self):
        """
            :return:True  -> 表示需要发布配置数据
                    False -> 表示不需要发布配置数据
        """
        return False

    def set_qos_num(self):
        """

        :return:
        """
        return 5


def update_device_basic_info(data):
    """

    :param data:
    :return:
    """
    try:
        upperpc_code_list, call_id_list = [], []
        device_code_list, device_code_name_map = [], {}
        for document in data:
            upperpc_code = document.get('上位机编码', '')
            call_id = document.get('认证id', '')
            device_name = document.get('设备名称', '')
            device_code = document.get('设备编码', '')
            # upperpc_code = document.get('生产单元代号', '')
            # upperpc_code = document.get('生产单元名称', '')
            upperpc_code_list.append(upperpc_code)
            call_id_list.append(call_id)
            device_code_list.append(device_code)
            device_code_name_map.update({device_code: device_name})
        update_context("upperpc_code_list", list(set(upperpc_code_list)))
        update_context("call_id_list", list(set(call_id_list)))
        update_context("device_code_list", list(set(device_code_list)))
        update_context("device_code_name_map", device_code_name_map)

    except Exception as e:
        traceback.print_exc()
        get_logger().error("load_workshop_device_config_data error:%s", e)


msg_handler = {
    "WebLayout_produce_unit_import_application_used": update_device_basic_info,
}

my_consume_list = list(msg_handler.keys())


async def get_subscribe_message_cache():
    """

    :return:
    """
    subscribe_message = await rabbitmq_get_subscribe_message_cache()
    for message_key, message_data in subscribe_message.items():
        message = {'key': message_key, 'data': message_data}
        await process_mq_msg(message)
